package com.burgeon.backend.service.Impl;

import com.burgeon.backend.EnterpriseWeChat.service.EWInfoService;
import com.burgeon.backend.Rest.Template.Reviews.FindRetailInfo;
import com.burgeon.backend.Rest.coupon.util.CreateIntegral;
import com.burgeon.backend.SHOP.service.EmpNotificationMessageService;
import com.burgeon.backend.SHOP.service.ShopMessageTemplateService;
import com.burgeon.backend.SHOPBACKEND.service.BackendTemplateService;
import com.burgeon.backend.Util.RedisUtil;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.entity.RetailData;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.service.CouponService;
import com.burgeon.backend.service.MessageTemplateService;
import com.burgeon.backend.service.QueueService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

@Service
public class QueueServiceImpl implements QueueService {

    private final static Log logger = LogFactory.getLog(QueueService.class);

    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private MessageTemplateService messageTemplateService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ShopMessageTemplateService shopMessageTemplateService;
    @Autowired
    private EmpNotificationMessageService empNotificationMessageService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private EWInfoService ewInfoService;
    @Autowired
    private BackendTemplateService backendTemplateService;

    private static final String QUEUELIST = "queuelist";

    public static void main(String[] args) throws InterruptedException {
        // 1. 创建定长线程池对象 & 设置线程池线程数量固定为3
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
        Runnable rr = () -> {
            //获取列表

                //执行任务 删除队列
                //记录成功/失败状态
                Runnable task = () -> {
                    // 2. 创建好Runnable类线程对象 & 需执行的任务
                    //执行成功删除任务

                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.err.println("线程:");
                    System.out.println(Thread.currentThread().getName());
                    System.out.println(((ThreadPoolExecutor) fixedThreadPool).getActiveCount()+"个");
                    System.out.println("执行任务啦");

                };
                // 3. 向线程池提交任务
                fixedThreadPool.execute(task);

        };
        rr.run();

    }


    @Override
    public void consumer() {

        // 1. 创建定长线程池对象 & 设置线程池线程数量固定为3
      //  ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);

        Runnable task = () -> {

            while (true) {
                String str = redisUtil.lPop(QUEUELIST);

                if (null == str) {
                    try {
                        Thread.sleep(1000);
                        continue;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                try {
                    Thread.sleep(100);
                    executeTheTask(str);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                System.out.println("执行任务啦");
            }

        };

        task.run();

    }


    //XF
    private boolean executeTheTask(String str) throws Exception {

        if (str==null){
            return false;
        }
        Map map = transStringToMap(str);
        String type = map.get("type").toString();
        System.err.println(str);
        boolean b = false;
        switch (type) {
            case "1": // 新用户送积分
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    logger.info("发送积分"+e.getMessage());
                }
                String token = map.get("token").toString();
                String name = map.get("name").toString();
                String phone = map.get("phone").toString();
                String openid = map.get("openid").toString();
                String integral = map.get("integral").toString();

                b = addIntegral(token, phone, name, openid, integral);

                logger.info("新用户送积分"+name+phone);
                break;
            case "2": // 未评价
                token = map.get("token").toString();
                openid = map.get("openid").toString();
                String orderId = map.get("orderId").toString();
                String price = map.get("price").toString();
                String goodsName = map.get("goodsName").toString();
                shopMessageTemplateService.sendOrderRate(openid,orderId,token,price,goodsName);
                break;
            case "3": // 超时订单
                token = map.get("token").toString();
                openid = map.get("openid").toString();
                empNotificationMessageService.sendEmpOvertime(openid,token);
                break;
            case "4": // 手工分单
                token = map.get("token").toString();
                openid = map.get("openid").toString();
                empNotificationMessageService.sendEmpDelivery(openid,token);
                break;
            case "5": // 砍价
                token = map.get("token").toString();
                openid = map.get("openid").toString();
                String now = map.get("now").toString();
                goodsName = map.get("goodsName").toString();
                shopMessageTemplateService.sendBargain(openid,token,now,goodsName);
                break;
            case "6": // 砍价
                token = map.get("token").toString();
                openid = map.get("openid").toString();
                now = map.get("now").toString();
                goodsName = map.get("goodsName").toString();
                orderId = map.get("orderId").toString();
                shopMessageTemplateService.sendGroup(openid,orderId,token,now,goodsName);
                break;
            case "7": //新用户送券
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    logger.info("发送优惠券"+e.getMessage());
                }
                token = map.get("token").toString();
                String id = map.get("id").toString();
                phone = map.get("phone").toString();
                addNewUserCoupon(id,phone,token);
                logger.info("新用户优惠券"+phone);
                break;
            case "8": //推荐新用户送券
                token = map.get("token").toString();
                id = map.get("id").toString();
                phone = map.get("phone").toString();
                addNewUserCoupon(id,phone,token);
                break;
            case "9": // 推荐新用户送积分
                token = map.get("token").toString();
                name = map.get("name").toString();
                phone = map.get("phone").toString();
                openid = map.get("openid").toString();
                integral = map.get("integral").toString();
                addRecommendIntegral(token, phone, name, openid, integral);
                break;
            case "10": // 尾款支付
                token = map.get("token").toString();
                goodsName = map.get("goodsName").toString();
                String finalMoney = map.get("finalMoney").toString();
                openid = map.get("openid").toString();
                String endTime = map.get("endTime").toString();
                shopMessageTemplateService.sendFinalPayMessageTemplate(goodsName,finalMoney,endTime,openid,token);
                break;
            case "11": // 订单发货
                token = map.get("token").toString();
                orderId = map.get("orderId").toString();
                String orderState = map.get("orderState").toString();
                openid = map.get("openid").toString();
                String date = map.get("date").toString();
                String address = map.get("address").toString();
                shopMessageTemplateService.sendOrderDelivery(orderId,orderState,date,address,openid,token);
                break;
            case "12": // 发送活动内容
                String account = map.get("account").toString();
                String first = map.get("first").toString();
                String keyword1 = map.get("keyword1").toString();
                openid = map.get("openid").toString();
                String keyword2 = map.get("keyword2").toString();
                String keyword3 = map.get("keyword3").toString();
                String keyword4 = map.get("keyword4").toString();
                String remark = map.get("remark").toString();
                String templateId = map.get("templateId").toString();
                messageTemplateService.SendMessageForActivity(account,openid,templateId,first,keyword1,keyword2,
                        keyword3,keyword4,remark);
                break;
            case "13": // 发送活动内容
                account = map.get("account").toString();
                first = map.get("first").toString();
                keyword1 = map.get("keyword1").toString();
                openid = map.get("openid").toString();
                keyword2 = map.get("keyword2").toString();
                keyword3 = map.get("keyword3").toString();
                remark = map.get("remark").toString();
                templateId = map.get("templateId").toString();
                messageTemplateService.SendMessageForYY(account,openid,templateId,first,keyword1,keyword2,
                        keyword3,remark);
                break;
            case "14": // 发送活动内容
                map.put("type", "14");
                String userid = map.get("userid").toString();
                orderId = map.get("orderId").toString();
                token = map.get("token").toString();
                Info info = GetInfo(token);

                FindRetailInfo findRetailInfo = new FindRetailInfo(info.getUrl(), info.getAccount(), info.getPassword());
                RetailData data = findRetailInfo.getData(orderId);

                if (data.getIsSelfRai().equals("是")){
                    System.err.println("====自提订单"+orderId);
                    ewInfoService.sendEmpNewOrderMiniZT(userid,orderId,token,data.getStore(),data.getSinceDate());
                }
                ewInfoService.sendEmpNewOrderMini(userid,orderId,token);
                break;
            case "16": // 发送活动内容  map.put("token", token);
                System.err.println("ffffffff");
                templateId = map.get("templateId").toString();
                token = map.get("token").toString();
                openid = map.get("openid").toString();
                String code = map.get("code").toString();
                String money = map.get("money").toString();
                String expiredTime = map.get("expiredTime").toString();
                id = map.get("id").toString();
                backendTemplateService.SendExpiredCouponTemplate(templateId,token,code,money,expiredTime,openid,id);
                break;
        }
        return b;
    }


    private void addNewUserCoupon(String id,String phone,String token) {

        couponService.addCoupon(id,phone,token);
    }

    /**
     * 新用户送积分 XF
     *
     * @param token
     * @param phone
     * @param name
     * @param openid
     * @param integral
     * @return
     */
    private boolean addIntegral(String token, String phone, String name, String openid, String integral) {

        Info info = GetInfoByToken(token);

        CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            createIntegral.getData(phone, "-" + integral);
            logger.error("新用户送积分" + phone);
            messageTemplateService.SendMessageForNewUser(token, openid, phone, integral, name);
        } catch (Exception e) {
            logger.error("新会员注册积分调整错误" + Arrays.toString(e.getStackTrace()) + e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 推荐新用户送积分
     * @param token
     * @param phone
     * @param name
     * @param openid
     * @param integral
     * @return
     */
    private boolean addRecommendIntegral(String token, String phone, String name, String openid, String integral) {

        Info info = GetInfoByToken(token);

        CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            createIntegral.getData(phone, "-" + integral);
            logger.error("推荐新用户送积分" + phone);
            messageTemplateService.SendMessageForRecommend(token, openid, phone, integral, name);
        } catch (Exception e) {
            logger.error("推荐新会员注册积分调整错误" + Arrays.toString(e.getStackTrace()) + e.getMessage());
            return false;
        }
        return true;
    }


    private Info GetInfoByToken(String token) {
        return accountMapper.GetTokenData(token);
    }

    /**
     * 新用户送券
     * @param id
     * @param phone
     * @param token
     */
    @Override
    public void putNewUserCoupon(String id, String phone, String token) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("type", "7");
        map.put("token", token);
        map.put("id", id);
        map.put("phone", phone);
        redisUtil.rPush(QUEUELIST,transMapToString(map));
    }

    /**
     * 添加任务 SC
     * 新用户送积分
     *
     * @param token
     */
    @Override
    public void putNewUserIntegral(String name, String phone, String openid,
                                   String integral, String token) {

        Map<String, String> map = new HashMap<String, String>();
        map.put("type", "1");
        map.put("token", token);
        map.put("name", name);
        map.put("phone", phone);
        map.put("openid", openid);
        map.put("integral", integral);
        redisUtil.rPush(QUEUELIST,transMapToString(map));


    }



    /**
     * x天未评价
     * @param openid
     * @param orderId
     * @param token
     * @param price
     * @param goodsName
     */
    @Override
    public void putOrderRate(String openid, String orderId,
                             String token,String price,String goodsName) {

        Map<String, String> map = new HashMap<String, String>();
        map.put("type", "2");
        map.put("token", token);
        map.put("orderId", orderId);
        map.put("price", price);
        map.put("openid", openid);
        map.put("goodsName", goodsName);
        redisUtil.rPush(QUEUELIST,transMapToString(map));


    }

    /**
     * 超时订单
     * @param openid
     * @param token
     */
    @Override
    public void putEmpOvertime(String openid, String token) {
        System.err.println("map");
        Map<String, String> map = new HashMap<String, String>();
        map.put("type", "3");
        map.put("token", token);
        map.put("openid", openid);
        redisUtil.rPush(QUEUELIST,transMapToString(map));
    }

    /**
     * 手工分单
     * @param openid
     * @param token
     */
    @Override
    public void putEmpDelivery(String openid, String token) {
        System.err.println("map");
        Map<String, String> map = new HashMap<String, String>();
        map.put("type", "4");
        map.put("token", token);
        map.put("openid", openid);
        redisUtil.rPush(QUEUELIST,transMapToString(map));
    }

    /**
     * 砍价成功
     * @param openid
     * @param token
     * @param now
     * @param goodsName
     */
    @Override
    public void putBargain(String openid, String token, String now, String goodsName) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("type", "5");
        map.put("token", token);
        map.put("openid", openid);
        map.put("now", now);
        map.put("goodsName", goodsName);
        redisUtil.rPush(QUEUELIST,transMapToString(map));
    }

    /**
     * 拼团成功
     * @param openid
     * @param token
     * @param now
     * @param goodsName
     */
    @Override
    public void putGroup(String openid, String orderId,String token, String now, String goodsName) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("type", "6");
        map.put("token", token);
        map.put("openid", openid);
        map.put("now", now);
        map.put("goodsName", goodsName);
        map.put("orderId", orderId);
        redisUtil.rPush(QUEUELIST,transMapToString(map));
    }

    @Override
    public void putRecommendUserCoupon(String id, String phone, String token) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("type", "8");
        map.put("token", token);
        map.put("id", id);
        map.put("phone", phone);
        redisUtil.rPush(QUEUELIST,transMapToString(map));
    }

    @Override
    public void putRecommendUserIntegral(String name, String phone, String openid, String integral, String token) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("type", "9");
        map.put("token", token);
        map.put("name", name);
        map.put("phone", phone);
        map.put("openid", openid);
        map.put("integral", integral);
        redisUtil.rPush(QUEUELIST,transMapToString(map));
    }

    /**
     * 尾款支付
     * @param goodsName
     * @param finalMoney
     * @param endTime
     * @param openid
     * @param token
     */
    @Override
    public void payingBalancePayment(String goodsName,String finalMoney,String endTime,String openid,String token) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("type", "10");
        map.put("token", token);
        map.put("goodsName", goodsName);
        map.put("finalMoney", finalMoney);
        map.put("endTime", endTime);
        map.put("openid", openid);
        redisUtil.rPush(QUEUELIST,transMapToString(map));
    }

    /**
     * 订单发货
     * @param orderId
     * @param orderState
     * @param date
     * @param address
     * @param openid
     * @param token
     */
    @Override
    public void putFinalPay(String orderId, String orderState, String date,String address,String openid,String token) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("type", "11");
        map.put("token", token);
        map.put("orderId", orderId);
        map.put("orderState", orderState);
        map.put("date", date);
        map.put("address", address);
        map.put("openid", openid);
        redisUtil.rPush(QUEUELIST,transMapToString(map));
    }

    @Override
    public void putVipActivity(String account,String openid, String templateId,String first,String keyword1,
                               String keyword2, String keyword3,String keyword4,String remark) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("type", "12");
        map.put("account", account);
        map.put("openid", openid);
        map.put("templateId", templateId);
        map.put("first", first);
        map.put("keyword1", keyword1);
        map.put("keyword2", keyword2);
        map.put("keyword3", keyword3);
        map.put("keyword4", keyword4);
        map.put("remark",remark);
        redisUtil.rPush(QUEUELIST,transMapToString(map));
    }

    @Override
    public void putVipYuYue(String account, String openid, String templateId, String first,
                               String keyword1, String keyword2, String keyword3, String remark) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("type", "13");
        map.put("account", account);
        map.put("openid", openid);
        map.put("templateId", templateId);
        map.put("first", first);
        map.put("keyword1", keyword1);
        map.put("keyword2", keyword2);
        map.put("keyword3", keyword3);
        map.put("remark",remark);
        redisUtil.rPush(QUEUELIST,transMapToString(map));
    }

    /**
     * 给企业微信导购发送新订单通知
     * @param orderId
     * @param token
     */
    @Override
    public void sendEWEmpNewOrder(String userid,String orderId, String token) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("type", "14");
        map.put("userid", userid);
        map.put("orderId", orderId);
        map.put("token", token);
        redisUtil.rPush(QUEUELIST,transMapToString(map));
    }

    @Override
    public void putExpiredCouponTemplate(String templateId, String token, String code, String money, String expiredTime, String openid,String id) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("type", "16");
        map.put("token", token);
        map.put("openid", openid);
        map.put("templateId", templateId);
        map.put("code", code);
        map.put("money", money);
        map.put("expiredTime", expiredTime);
        map.put("id",id);
        System.err.println(map);
        redisUtil.rPush(QUEUELIST,transMapToString(map));
    }


    /**
     * 方法名称:transStringToMap
     * 传入参数:mapString 形如 username'chenziwen^password'1234
     * 返回值:Map
     */
    public static Map transStringToMap(String mapString){
        Map map = new HashMap();
        java.util.StringTokenizer items;
        for(StringTokenizer entrys = new StringTokenizer(mapString, "^");entrys.hasMoreTokens();
            map.put(items.nextToken(), items.hasMoreTokens() ? ((Object) (items.nextToken())) : null))
            items = new StringTokenizer(entrys.nextToken(), "'");
        System.err.println(map);
        return map;
    }
    // map转string
    public static String transMapToString(Map map){
        java.util.Map.Entry entry;
        StringBuffer sb = new StringBuffer();
        for(Iterator iterator = map.entrySet().iterator(); iterator.hasNext();)
        {
            entry = (java.util.Map.Entry)iterator.next();
            sb.append(entry.getKey().toString()).append( "'" ).append(null==entry.getValue()?"":
                    entry.getValue().toString()).append (iterator.hasNext() ? "^" : "");
        }
        return sb.toString();
    }

    private Info GetInfo(String token) {
        return accountMapper.GetTokenData(token);
    }


}
